package com.margo.project.transaction.simple.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.margo.project.transaction.throwable.MargoRollbackThrowable;



@Service
public class JdbcTemplateTraService implements ApplicationContextAware{
	

	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
		
	}
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Transactional(rollbackFor=MargoRollbackThrowable.class)
	public int rollback() throws MargoRollbackThrowable {
		jdbcTemplate.update("update sw_build_plan set sw_build_plan.project_id=2");

		int result=1;
		if(result==1) {
			throw new MargoRollbackThrowable();
		}
		logger.info("抛出MargoRollback");
		return 1;	
	}
	
	@Transactional
	public int commit() throws MargoRollbackThrowable {
		jdbcTemplate.update("update sw_build_plan set sw_build_plan.project_id=2");

		int result=1;
		if(result==1) {
			throw new MargoRollbackThrowable();
		}
		logger.info("抛出MargoRollback");
		return 1;	
	}

	
	
	@Transactional
	public void listener() {
		int result=2;
		ApplicationEvent event=new ApplicationEvent(result) {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
		};
		jdbcTemplate.update("update sw_build_plan set sw_build_plan.project_id=4");
		applicationContext.publishEvent(event);
	}

}
